package com.tanhua.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //添加好友
    public void contacts(Long myId, Long userId) {
        Friend friend = new Friend();
        friend.setId(new ObjectId());
        friend.setUserId(myId);
        friend.setFriendId(userId);
        friend.setCreated(System.currentTimeMillis());
        mongoTemplate.save(friend);

        Friend friend2 = new Friend();
        friend2.setId(new ObjectId());
        friend2.setUserId(userId);
        friend2.setFriendId(myId);
        friend2.setCreated(System.currentTimeMillis());
        mongoTemplate.save(friend2);
    }

    //查询好友列表
    public PageBeanVo findContacts(Integer page, Integer pagesize, Long id) {

        Query query = new Query(Criteria.where("UserId").is(id));
        query.with(new Sort(Sort.Direction.DESC,"created"));
        query.skip((page-1)*pagesize).limit(pagesize);
        List<Friend> friendsList = mongoTemplate.find(query, Friend.class);
        Long count = mongoTemplate.count(query, Friend.class);

        return new PageBeanVo(page,pagesize,count,friendsList);
    }

    @Override
    public boolean isFriend(Long userId, Long uid) {

        Query query = new Query(Criteria.where("userId").is(userId)
        .and("friendId").is(uid));
        long count = mongoTemplate.count(query, Friend.class);

        return count==0?false:true;
    }

    //删除好友关系
    public void deleteFriend(Long id, Long uid) {

        Query query = new Query(Criteria.where("userId").is(id)
        .and("friendId").is(uid));
        mongoTemplate.remove(query,Friend.class);

        Query query2 = new Query(Criteria.where("userId").is(uid)
                .and("friendId").is(id));
        mongoTemplate.remove(query2,Friend.class);
    }
}
